package com.cqndt.disaster.device.timer;

import com.alibaba.fastjson.JSON;
import com.cqndt.disaster.device.common.influxdb.InfluxDBConnect;
import com.cqndt.disaster.device.common.util.HttpClientUtil;
import com.cqndt.disaster.device.common.util.UpdatePropertyUtil;
import com.cqndt.disaster.device.dao.*;
import com.cqndt.disaster.device.dao.TabUnionMapper;
import com.cqndt.disaster.device.dao.warn.WarnPlanMapper;
import com.cqndt.disaster.device.domain.TabAlarmInfo;
import com.cqndt.disaster.device.domain.TabDeviceException;
import com.cqndt.disaster.device.domain.TabOnline;
import com.cqndt.disaster.device.domain.WarnPlan;
import com.cqndt.disaster.device.message.SudasSmsUtil;
import com.cqndt.disaster.device.utils.JSONUtils;
import com.cqndt.disaster.device.vo.TabMsgRecord;
import com.cqndt.disaster.device.websocket.WebSocketServer;
import org.influxdb.dto.QueryResult;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.utils.SerializationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author qingqinchao
 */
@Component
public class DataTimer {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private DataCmccMapper dataCmccMapper;
    @Autowired
    private TabWarnSettingMapper tabWarnSettingMapper;
    @Autowired
    private TabMonitorMapper tabMonitorMapper;
    @Autowired
    private TabAlarmInfoMapper tabAlarmInfoMapper;
    @Autowired
    private TabDeviceMapper tabDeviceMapper;
    @Autowired
    private TabOnlineMapper tabOnlineMapper;
    @Autowired
    private InfluxDBConnect influxDBConnect;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private TabSensorMapper tabSensorMapper;
    @Autowired
    private TabDeviceExceptionMapper tabDeviceExceptionMapper;
    @Autowired
    private TabUnionMapper tabUnionMapper;

    @Autowired
    TabMsgRecordMapper tabMsgRecordMapper;

    @Autowired
    WarnPlanMapper warnPlanMapper;


    @Value("${path-record-time}")
    private String recordTimePath;
    @Value("${token-url}")
    private String tokenUrl;
    @Value("${gnss-data-url}")
    private String gnssDataUrl;
    @Value("${add-time}")
    private int addTime;
    @Value("${lgd-token-url}")
    private String lgdTokenUrl;
    @Value("${lgd-push-url}")
    private String lgdPushUrl;

    private static Map<String, String> map = new HashMap<>(16);

    @Async("taskExecutor")
    @Scheduled(initialDelay = 5000, fixedRate = 20000)
    public void dataTimer() {
        List<Map<String, String>> mapList = dataCmccMapper.selectNo();
        for (Map<String, String> map : mapList) {
            String sensorNo = map.get("imei");
            String type = map.get("value");
            if (sensorNo != null && type != null) {
                HashOperations<String, Object, Object> vo = stringRedisTemplate.opsForHash();
                switch (type) {
                    case "QINGXIE":
                        String measurementXQX = "tbs_dm_qxy_x";
                        String dsIdXQX = "3345_0_5702";
                        String lastRecordTimeXQX = dataCmccMapper.selectLastRecordTime(sensorNo, dsIdXQX);
                        if (lastRecordTimeXQX == null) {
                            lastRecordTimeXQX = influxDBConnect.selectLastRecordTime(sensorNo, measurementXQX);
                            if (lastRecordTimeXQX == null) {
                                lastRecordTimeXQX = "2000-01-01 00:00:00";
                            }
                        }
                        if (lastRecordTimeXQX != null) {
                            List<Map<String, Object>> fieldsX = dataCmccMapper.selectQingXieXByTime(sensorNo, lastRecordTimeXQX);
                            if (fieldsX != null && fieldsX.size() > 0) {
                                for (Map<String, Object> mapField : fieldsX) {
                                    Double value = Double.valueOf(mapField.get("value").toString());
                                    value = value > 180.0 ? (value - 360.0) : value;
                                    //告警判断
                                    WarnPlan warnPlan = new WarnPlan("qxx", BigDecimal.valueOf(value), sensorNo, 2);
                                    warnPlanMapper.insertWarnPlan(warnPlan);

                                    String currentTime = mapField.get("currentTime").toString();
                                    String time = timestampToString(currentTime);
                                    vo.put(sensorNo, "time", time);
                                    vo.put(sensorNo, "value", value.toString());
//                                    warnPush(sensorNo, "", currentTime, value);
                                    String format = String.format("%.3f", value);
                                    mapField.put("value", format);
                                    //联合告警任务表插入数据
                                    tabUnionMapper.insert(dsIdXQX, value,sensorNo);
                                }

                                int i = dataCmccMapper.selectIsLastRecordTime(sensorNo, dsIdXQX);
                                if (i == 0) {
                                    String lRTime = timestampToString(fieldsX.get(fieldsX.size() - 1).get("currentTime").toString());
                                    dataCmccMapper.insertLastRecordTime(sensorNo, dsIdXQX, lRTime);
                                } else {
                                    String lRTime = timestampToString(fieldsX.get(fieldsX.size() - 1).get("currentTime").toString());
                                    dataCmccMapper.updateLastRecordTime(sensorNo, dsIdXQX, lRTime);
                                }
                                saveData(sensorNo, measurementXQX, fieldsX);
                            }
                        }

                        String measurementYQX = "tbs_dm_qxy_y";
                        String dsIdYQX = "3345_0_5703";
                        String lastRecordTimeYQX = dataCmccMapper.selectLastRecordTime(sensorNo, dsIdYQX);
                        if (lastRecordTimeYQX == null) {
                            lastRecordTimeYQX = influxDBConnect.selectLastRecordTime(sensorNo, measurementXQX);
                            if (lastRecordTimeYQX == null) {
                                lastRecordTimeYQX = "2000-01-01 00:00:00";
                            }
                        }
                        if (lastRecordTimeYQX != null) {
                            List<Map<String, Object>> fieldsY = dataCmccMapper.selectQingXieYByTime(sensorNo, lastRecordTimeYQX);
                            if (fieldsY != null && fieldsY.size() > 0) {

                                for (Map<String, Object> mapField : fieldsY) {
                                    Double value = Double.valueOf(mapField.get("value").toString());
                                    value = value > 180.0 ? (value - 360.0) : value;
                                    //告警判断
                                    WarnPlan warnPlan = new WarnPlan("qxy", BigDecimal.valueOf(value), sensorNo, 2);
                                    warnPlanMapper.insertWarnPlan(warnPlan);

                                    String currentTime = mapField.get("currentTime").toString();
                                    String time = timestampToString(currentTime);
                                    vo.put(sensorNo, "time", time);
                                    vo.put(sensorNo, "value", value.toString());
//                                    warnPush(sensorNo, "", currentTime, value);
                                    String format = String.format("%.3f", value);
                                    mapField.put("value", format);
                                    //联合告警任务表插入数据
                                    tabUnionMapper.insert(dsIdXQX, value,sensorNo);
                                }

                                int i = dataCmccMapper.selectIsLastRecordTime(sensorNo, dsIdYQX);
                                if (i == 0) {
                                    String lRTime = timestampToString(fieldsY.get(fieldsY.size() - 1).get("currentTime").toString());
                                    dataCmccMapper.insertLastRecordTime(sensorNo, dsIdYQX, lRTime);
                                } else {
                                    String lRTime = timestampToString(fieldsY.get(fieldsY.size() - 1).get("currentTime").toString());
                                    dataCmccMapper.updateLastRecordTime(sensorNo, dsIdYQX, lRTime);
                                }
                                saveData(sensorNo, measurementYQX, fieldsY);
                            }
                        }

                        String measurementZQX = "tbs_dm_qxy_z";
                        String dsIdZQX = "3345_0_5704";
                        String lastRecordTimeZQX = dataCmccMapper.selectLastRecordTime(sensorNo, dsIdZQX);
                        if (lastRecordTimeZQX == null) {
                            lastRecordTimeZQX = influxDBConnect.selectLastRecordTime(sensorNo, measurementXQX);
                            if (lastRecordTimeZQX == null) {
                                lastRecordTimeZQX = "2000-01-01 00:00:00";
                            }
                        }
                        if (lastRecordTimeZQX != null) {
                            List<Map<String, Object>> fieldsZ = dataCmccMapper.selectQingXieZByTime(sensorNo, lastRecordTimeZQX);
                            if (fieldsZ != null && fieldsZ.size() > 0) {
                                for (Map<String, Object> mapField : fieldsZ) {
                                    Double value = Double.valueOf(mapField.get("value").toString());
                                    value = value > 180.0 ? (value - 360.0) : value;
                                    //告警判断
                                    WarnPlan warnPlan = new WarnPlan("qxz", BigDecimal.valueOf(value), sensorNo, 2);
                                    warnPlanMapper.insertWarnPlan(warnPlan);

                                    String currentTime = mapField.get("currentTime").toString();
                                    String time = timestampToString(currentTime);
                                    vo.put(sensorNo, "time", time);
                                    vo.put(sensorNo, "value", value.toString());
                                    warnPush(sensorNo, "", currentTime, value);
                                    String format = String.format("%.3f", value);
                                    mapField.put("value", format);
                                    //联合告警任务表插入数据
                                    tabUnionMapper.insert(dsIdXQX, value,sensorNo);
                                }
                                int i = dataCmccMapper.selectIsLastRecordTime(sensorNo, dsIdZQX);
                                if (i == 0) {
                                    String lRTime = timestampToString(fieldsZ.get(fieldsZ.size() - 1).get("currentTime").toString());
                                    dataCmccMapper.insertLastRecordTime(sensorNo, dsIdZQX, lRTime);
                                } else {
                                    String lRTime = timestampToString(fieldsZ.get(fieldsZ.size() - 1).get("currentTime").toString());
                                    dataCmccMapper.updateLastRecordTime(sensorNo, dsIdZQX, lRTime);
                                }
                                saveData(sensorNo, measurementZQX, fieldsZ);
                            }
                        }
                        break;
                    case "BIAOQING":
                        String measurementXPQ = "tbs_ptqcbxy_wy_x";
                        String dsIdXPQ = "3345_0_5702";
                        String lastRecordTimeXPQ = dataCmccMapper.selectLastRecordTime(sensorNo, dsIdXPQ);
                        if (lastRecordTimeXPQ == null) {
                            lastRecordTimeXPQ = influxDBConnect.selectLastRecordTime(sensorNo + "倾斜".hashCode(), measurementXPQ);
                            if (lastRecordTimeXPQ == null) {
                                lastRecordTimeXPQ = "2000-01-01 00:00:00";
                            }
                        }
                        if (lastRecordTimeXPQ != null) {
                            List<Map<String, Object>> fieldsX = dataCmccMapper.selectQingXieXByTime(sensorNo, lastRecordTimeXPQ);
                            if (fieldsX != null && fieldsX.size() > 0) {
                                for (Map<String, Object> mapField : fieldsX) {
                                    Double value = Double.valueOf(mapField.get("value").toString());
                                    value = value > 180.0 ? (value - 360.0) : value;
                                    //告警判断
                                    String currentTime = mapField.get("currentTime").toString();
                                    String time = timestampToString(currentTime);
                                    vo.put(sensorNo + "倾斜".hashCode(), "time", time);
                                    vo.put(sensorNo + "倾斜".hashCode(), "value", value.toString());
//                                    warnPush(sensorNo + "倾斜".hashCode(), "", currentTime, value);
                                    String format = String.format("%.3f", value);
                                    mapField.put("value", format);
                                    //联合告警任务表插入数据
                                    tabUnionMapper.insert(dsIdXPQ, value,sensorNo);
                                }
                                int i = dataCmccMapper.selectIsLastRecordTime(sensorNo, dsIdXPQ);
                                if (i == 0) {
                                    String lRTime = timestampToString(fieldsX.get(fieldsX.size() - 1).get("currentTime").toString());
                                    dataCmccMapper.insertLastRecordTime(sensorNo, dsIdXPQ, lRTime);
                                } else {
                                    String lRTime = timestampToString(fieldsX.get(fieldsX.size() - 1).get("currentTime").toString());
                                    dataCmccMapper.updateLastRecordTime(sensorNo, dsIdXPQ, lRTime);
                                }
                                saveData(sensorNo + "倾斜".hashCode(), measurementXPQ, fieldsX);
                            }
                        }

                        String measurementYPQ = "tbs_ptqcbxy_wy_y";
                        String dsIdYPQ = "3345_0_5703";
                        String lastRecordTimeYPQ = dataCmccMapper.selectLastRecordTime(sensorNo, dsIdYPQ);
                        if (lastRecordTimeYPQ == null) {
                            lastRecordTimeYPQ = influxDBConnect.selectLastRecordTime(sensorNo + "倾斜".hashCode(), measurementYPQ);
                            if (lastRecordTimeYPQ == null) {
                                lastRecordTimeYPQ = "2000-01-01 00:00:00";
                            }
                        }
                        if (lastRecordTimeYPQ != null) {
                            List<Map<String, Object>> fieldsY = dataCmccMapper.selectQingXieYByTime(sensorNo, lastRecordTimeYPQ);
                            if (fieldsY != null && fieldsY.size() > 0) {
                                for (Map<String, Object> mapField : fieldsY) {
                                    Double value = Double.valueOf(mapField.get("value").toString());
                                    value = value > 180.0 ? (value - 360.0) : value;
                                    //告警判断
                                    String currentTime = mapField.get("currentTime").toString();
                                    String time = timestampToString(currentTime);
                                    vo.put(sensorNo + "倾斜".hashCode(), "time", time);
                                    vo.put(sensorNo + "倾斜".hashCode(), "value", value.toString());
//                                    warnPush(sensorNo + "倾斜".hashCode(), "", currentTime, value);
                                    String format = String.format("%.3f", value);
                                    mapField.put("value", format);
                                    //联合告警任务表插入数据
                                    tabUnionMapper.insert(dsIdXPQ, value,sensorNo);
                                }
                                int i = dataCmccMapper.selectIsLastRecordTime(sensorNo, dsIdYPQ);
                                if (i == 0) {
                                    String lRTime = timestampToString(fieldsY.get(fieldsY.size() - 1).get("currentTime").toString());
                                    dataCmccMapper.insertLastRecordTime(sensorNo, dsIdYPQ, lRTime);
                                } else {
                                    String lRTime = timestampToString(fieldsY.get(fieldsY.size() - 1).get("currentTime").toString());
                                    dataCmccMapper.updateLastRecordTime(sensorNo, dsIdYPQ, lRTime);
                                }
                                saveData(sensorNo + "倾斜".hashCode(), measurementYPQ, fieldsY);
                            }
                        }

                        String measurementZPQ = "tbs_ptqcbxy_wy_z";
                        String dsIdZPQ = "3345_0_5704";
                        String lastRecordTimeZPQ = dataCmccMapper.selectLastRecordTime(sensorNo, dsIdZPQ);
                        if (lastRecordTimeZPQ == null) {
                            lastRecordTimeZPQ = influxDBConnect.selectLastRecordTime(sensorNo + "倾斜".hashCode(), measurementZPQ);
                            if (lastRecordTimeZPQ == null) {
                                lastRecordTimeZPQ = "2000-01-01 00:00:00";
                            }
                        }
                        if (lastRecordTimeZPQ != null) {
                            List<Map<String, Object>> fieldsZ = dataCmccMapper.selectQingXieZByTime(sensorNo, lastRecordTimeZPQ);
                            if (fieldsZ != null && fieldsZ.size() > 0) {
                                for (Map<String, Object> mapField : fieldsZ) {
                                    Double value = Double.valueOf(mapField.get("value").toString());
                                    value = value > 180.0 ? (value - 360.0) : value;
                                    //告警判断
                                    String currentTime = mapField.get("currentTime").toString();
                                    String time = timestampToString(currentTime);
                                    vo.put(sensorNo + "倾斜".hashCode(), "time", time);
                                    vo.put(sensorNo + "倾斜".hashCode(), "value", value.toString());
//                                    warnPush(sensorNo + "倾斜".hashCode(), "", currentTime, value);
                                    String format = String.format("%.3f", value);
                                    mapField.put("value", format);
                                    //联合告警任务表插入数据
                                    tabUnionMapper.insert(dsIdXPQ, value,sensorNo);
                                }
                                int i = dataCmccMapper.selectIsLastRecordTime(sensorNo, dsIdZPQ);
                                if (i == 0) {
                                    String lRTime = timestampToString(fieldsZ.get(fieldsZ.size() - 1).get("currentTime").toString());
                                    dataCmccMapper.insertLastRecordTime(sensorNo, dsIdZPQ, lRTime);
                                } else {
                                    String lRTime = timestampToString(fieldsZ.get(fieldsZ.size() - 1).get("currentTime").toString());
                                    dataCmccMapper.updateLastRecordTime(sensorNo, dsIdZPQ, lRTime);
                                }
                                saveData(sensorNo + "倾斜".hashCode(), measurementZPQ, fieldsZ);
                            }
                        }

                        String measurementWXLX = "tbs_ptqcbxy_lx_x";
                        String dsIdWXLX = "3330_0_5700";
                        String lastRecordTimeWXLX = dataCmccMapper.selectLastRecordTime(sensorNo, dsIdWXLX);
                        if (lastRecordTimeWXLX == null) {
                            lastRecordTimeWXLX = influxDBConnect.selectLastRecordTime(sensorNo + "拉线".hashCode(), measurementWXLX);
                            if (lastRecordTimeWXLX == null) {
                                lastRecordTimeWXLX = "2000-01-01 00:00:00";
                            }
                        }
                        if (lastRecordTimeWXLX != null) {
                            List<Map<String, Object>> fieldsX = dataCmccMapper.selectQingXieWXByTime(sensorNo, lastRecordTimeWXLX);
                            if (fieldsX != null && fieldsX.size() > 0) {
                                for (Map<String, Object> mapField : fieldsX) {
                                    Double value = Double.valueOf(mapField.get("value").toString());
                                    value = value > 4000 ? (value - 5000) : value;
                                    //告警判断
                                    WarnPlan warnPlan = new WarnPlan("lxx", BigDecimal.valueOf(value), sensorNo, 1);
                                    warnPlanMapper.insertWarnPlan(warnPlan);

                                    String currentTime = mapField.get("currentTime").toString();
                                    String time = timestampToString(currentTime);
                                    vo.put(sensorNo + "拉线".hashCode(), "time", time);
                                    vo.put(sensorNo + "拉线".hashCode(), "value", value.toString());
//                                    warnPush(sensorNo + "拉线".hashCode(), "", currentTime, value);
                                    String format = String.format("%.3f", value);
                                    mapField.put("value", format);
                                    //联合告警任务表插入数据
                                    tabUnionMapper.insert(dsIdXPQ, value,sensorNo);
                                }
                                int i = dataCmccMapper.selectIsLastRecordTime(sensorNo, dsIdWXLX);
                                if (i == 0) {
                                    String lRTime = timestampToString(fieldsX.get(fieldsX.size() - 1).get("currentTime").toString());
                                    dataCmccMapper.insertLastRecordTime(sensorNo, dsIdWXLX, lRTime);
                                } else {
                                    String lRTime = timestampToString(fieldsX.get(fieldsX.size() - 1).get("currentTime").toString());
                                    dataCmccMapper.updateLastRecordTime(sensorNo, dsIdWXLX, lRTime);
                                }
                                saveData(sensorNo + "拉线".hashCode(), measurementWXLX, fieldsX);
                            }
                        }

                        String measurementWXLY = "tbs_ptqcbxy_lx_y";
                        String dsIdWXLY = "3330_1_5700";
                        String lastRecordTimeWXLY = dataCmccMapper.selectLastRecordTime(sensorNo, dsIdWXLY);
                        if (lastRecordTimeWXLY == null) {
                            lastRecordTimeWXLY = influxDBConnect.selectLastRecordTime(sensorNo + "拉线".hashCode(), measurementWXLY);
                            if (lastRecordTimeWXLY == null) {
                                lastRecordTimeWXLY = "2000-01-01 00:00:00";
                            }
                        }
                        if (lastRecordTimeWXLY != null) {
                            List<Map<String, Object>> fieldsY = dataCmccMapper.selectQingXieWYByTime(sensorNo, lastRecordTimeWXLY);
                            if (fieldsY != null && fieldsY.size() > 0) {
                                for (Map<String, Object> mapField : fieldsY) {
                                    Double value = Double.valueOf(mapField.get("value").toString());
                                    value = value > 4000 ? (value - 5000) : value;
                                    //告警判断
                                    //告警判断
                                    WarnPlan warnPlan = new WarnPlan("lxy", BigDecimal.valueOf(value), sensorNo, 1);
                                    warnPlanMapper.insertWarnPlan(warnPlan);

                                    String currentTime = mapField.get("currentTime").toString();
                                    String time = timestampToString(currentTime);
                                    vo.put(sensorNo + "拉线".hashCode(), "time", time);
                                    vo.put(sensorNo + "拉线".hashCode(), "value", value.toString());
//                                    warnPush(sensorNo + "拉线".hashCode(), "", currentTime, value);
                                    String format = String.format("%.3f", value);
                                    mapField.put("value", format);
                                    //联合告警任务表插入数据
                                    tabUnionMapper.insert(dsIdXPQ, value,sensorNo);
                                }
                                int i = dataCmccMapper.selectIsLastRecordTime(sensorNo, dsIdWXLY);
                                if (i == 0) {
                                    String lRTime = timestampToString(fieldsY.get(fieldsY.size() - 1).get("currentTime").toString());
                                    dataCmccMapper.insertLastRecordTime(sensorNo, dsIdWXLY, lRTime);
                                } else {
                                    String lRTime = timestampToString(fieldsY.get(fieldsY.size() - 1).get("currentTime").toString());
                                    dataCmccMapper.updateLastRecordTime(sensorNo, dsIdWXLY, lRTime);
                                }
                                saveData(sensorNo + "拉线".hashCode(), measurementWXLY, fieldsY);
                            }
                        }

                        String measurementWXLZ = "tbs_ptqcbxy_lx_z";
                        String dsIdWXLZ = "3330_2_5700";
                        String lastRecordTimeWXLZ = dataCmccMapper.selectLastRecordTime(sensorNo, dsIdWXLZ);
                        if (lastRecordTimeWXLZ == null) {
                            lastRecordTimeWXLZ = influxDBConnect.selectLastRecordTime(sensorNo + "拉线".hashCode(), measurementWXLZ);
                            if (lastRecordTimeWXLZ == null) {
                                lastRecordTimeWXLZ = "2000-01-01 00:00:00";
                            }
                        }
                        if (lastRecordTimeWXLZ != null) {
                            List<Map<String, Object>> fieldsZ = dataCmccMapper.selectQingXieWZByTime(sensorNo, lastRecordTimeWXLZ);
                            if (fieldsZ != null && fieldsZ.size() > 0) {
                                for (Map<String, Object> mapField : fieldsZ) {
                                    Double value = Double.valueOf(mapField.get("value").toString());
                                    value = value > 4000 ? (value - 5000) : value;
                                    //告警判断
                                    WarnPlan warnPlan = new WarnPlan("lxz", BigDecimal.valueOf(value), sensorNo, 1);
                                    warnPlanMapper.insertWarnPlan(warnPlan);

                                    String currentTime = mapField.get("currentTime").toString();
                                    String time = timestampToString(currentTime);
                                    vo.put(sensorNo + "拉线".hashCode(), "time", time);
                                    vo.put(sensorNo + "拉线".hashCode(), "value", value.toString());
//                                    warnPush(sensorNo + "拉线".hashCode(), "", currentTime, value);
                                    String format = String.format("%.3f", value);
                                    mapField.put("value", format);
                                    //联合告警任务表插入数据
                                    tabUnionMapper.insert(dsIdXPQ, value,sensorNo);
                                }
                                int i = dataCmccMapper.selectIsLastRecordTime(sensorNo, dsIdWXLZ);
                                if (i == 0) {
                                    String lRTime = timestampToString(fieldsZ.get(fieldsZ.size() - 1).get("currentTime").toString());
                                    dataCmccMapper.insertLastRecordTime(sensorNo, dsIdWXLZ, lRTime);
                                } else {
                                    String lRTime = timestampToString(fieldsZ.get(fieldsZ.size() - 1).get("currentTime").toString());
                                    dataCmccMapper.updateLastRecordTime(sensorNo, dsIdWXLZ, lRTime);
                                }
                                saveData(sensorNo + "拉线".hashCode(), measurementWXLZ, fieldsZ);
                            }
                        }
                        break;
                    case "DLF":
                        String measurementDLX = "tbs_liefeng_qj_x";
                        String dsIdDLX = "3345_0_5702";
                        String lastRecordTimeDLX = dataCmccMapper.selectLastRecordTime(sensorNo, dsIdDLX);
                        if (lastRecordTimeDLX == null) {
                            lastRecordTimeDLX = influxDBConnect.selectLastRecordTime(sensorNo + "倾斜".hashCode(), measurementDLX);
                            if (lastRecordTimeDLX == null) {
                                lastRecordTimeDLX = "2000-01-01 00:00:00";
                            }
                        }
                        if (lastRecordTimeDLX != null) {
                            List<Map<String, Object>> fieldsX = dataCmccMapper.selectQingXieXByTime(sensorNo, lastRecordTimeDLX);
                            if (fieldsX != null && fieldsX.size() > 0) {
                                System.out.println("MYMAP=================================================" + fieldsX);
                                System.out.println("传感器编号==========================" + sensorNo);
                                for (Map<String, Object> mapField : fieldsX) {
                                    Double value = Double.valueOf(mapField.get("value").toString());

                                    WarnPlan warnPlan = new WarnPlan("x", BigDecimal.valueOf(value), sensorNo, 0);
                                    warnPlanMapper.insertWarnPlan(warnPlan);

                                    //告警判断
//                                    warnPush(sensorNo + "倾斜".hashCode(), "x", currentTime, value);

                                    String currentTime = mapField.get("currentTime") + "";
                                    String time = timestampToString(currentTime);
                                    vo.put(sensorNo + "倾斜".hashCode() + "x", "time", time);
                                    vo.put(sensorNo + "倾斜".hashCode() + "x", "value", value.toString());
                                    //联合告警任务表插入数据
                                    tabUnionMapper.insert(dsIdDLX, value,sensorNo);
                                }
                                int i = dataCmccMapper.selectIsLastRecordTime(sensorNo, dsIdDLX);
                                if (i == 0) {
                                    String lRTime = timestampToString(fieldsX.get(fieldsX.size() - 1).get("currentTime").toString());
                                    dataCmccMapper.insertLastRecordTime(sensorNo, dsIdDLX, lRTime);
                                } else {
                                    String lRTime = timestampToString(fieldsX.get(fieldsX.size() - 1).get("currentTime").toString());
                                    dataCmccMapper.updateLastRecordTime(sensorNo, dsIdDLX, lRTime);
                                }
                                saveData(sensorNo + "倾斜".hashCode(), measurementDLX, fieldsX);
                            }
                        }

                        String measurementDLY = "tbs_liefeng_qj_y";
                        String dsIdDLY = "3345_0_5703";
                        String lastRecordTimeDLY = dataCmccMapper.selectLastRecordTime(sensorNo, dsIdDLY);
                        if (lastRecordTimeDLY == null) {
                            lastRecordTimeDLY = influxDBConnect.selectLastRecordTime(sensorNo + "倾斜".hashCode(), measurementDLY);
                            if (lastRecordTimeDLY == null) {
                                lastRecordTimeDLY = "2000-01-01 00:00:00";
                            }
                        }
                        if (lastRecordTimeDLY != null) {
                            List<Map<String, Object>> fieldsY = dataCmccMapper.selectQingXieYByTime(sensorNo, lastRecordTimeDLY);
                            if (fieldsY != null && fieldsY.size() > 0) {
                                System.out.println("MYMAP=================================================" + fieldsY);
                                System.out.println("传感器编号==========================" + sensorNo);
                                for (Map<String, Object> mapField : fieldsY) {
                                    Double value = Double.valueOf(mapField.get("value").toString());
                                    //告警判断

                                    WarnPlan warnPlan = new WarnPlan("y", BigDecimal.valueOf(value), sensorNo, 0);
                                    warnPlanMapper.insertWarnPlan(warnPlan);

                                    String currentTime = mapField.get("currentTime") + "";
                                    String time = timestampToString(currentTime);
//                                    warnPush(sensorNo + "倾斜".hashCode(), "y", currentTime, value);
                                    vo.put(sensorNo + "倾斜".hashCode() + "y", "time", time);
                                    vo.put(sensorNo + "倾斜".hashCode() + "y", "value", value.toString());
                                    //联合告警任务表插入数据
                                    tabUnionMapper.insert(dsIdDLX, value,sensorNo);
                                }
                                int i = dataCmccMapper.selectIsLastRecordTime(sensorNo, dsIdDLY);
                                if (i == 0) {
                                    String lRTime = timestampToString(fieldsY.get(fieldsY.size() - 1).get("currentTime").toString());
                                    dataCmccMapper.insertLastRecordTime(sensorNo, dsIdDLY, lRTime);
                                } else {
                                    String lRTime = timestampToString(fieldsY.get(fieldsY.size() - 1).get("currentTime").toString());
                                    dataCmccMapper.updateLastRecordTime(sensorNo, dsIdDLY, lRTime);
                                }
                                saveData(sensorNo + "倾斜".hashCode(), measurementDLY, fieldsY);
                            }
                        }

                        String measurementDLZ = "tbs_liefeng_qj_z";
                        String dsIdDLZ = "3345_0_5704";
                        String lastRecordTimeDLZ = dataCmccMapper.selectLastRecordTime(sensorNo, dsIdDLZ);
                        if (lastRecordTimeDLZ == null) {
                            lastRecordTimeDLZ = influxDBConnect.selectLastRecordTime(sensorNo + "倾斜".hashCode(), measurementDLZ);
                            if (lastRecordTimeDLZ == null) {
                                lastRecordTimeDLZ = "2000-01-01 00:00:00";
                            }
                        }
                        if (lastRecordTimeDLZ != null) {
                            List<Map<String, Object>> fieldsZ = dataCmccMapper.selectQingXieZByTime(sensorNo, lastRecordTimeDLZ);
                            if (fieldsZ != null && fieldsZ.size() > 0) {
                                System.out.println("MYMAP=================================================" + fieldsZ);
                                System.out.println("传感器编号==========================" + sensorNo);
                                for (Map<String, Object> mapField : fieldsZ) {
                                    Double value = Double.valueOf(mapField.get("value").toString());

                                    WarnPlan warnPlan = new WarnPlan("z", BigDecimal.valueOf(value), sensorNo, 0);
                                    warnPlanMapper.insertWarnPlan(warnPlan);

                                    //告警判断
                                    String currentTime = mapField.get("currentTime") + "";
                                    String time = timestampToString(currentTime);
//                                    warnPush(sensorNo + "倾斜".hashCode(), "z", currentTime, value);
                                    vo.put(sensorNo + "倾斜".hashCode() + "z", "time", time);
                                    vo.put(sensorNo + "倾斜".hashCode() + "z", "value", value.toString());
                                    //联合告警任务表插入数据
                                    tabUnionMapper.insert(dsIdDLX, value,sensorNo);
                                }
                                int i = dataCmccMapper.selectIsLastRecordTime(sensorNo, dsIdDLZ);
                                if (i == 0) {
                                    String lRTime = timestampToString(fieldsZ.get(fieldsZ.size() - 1).get("currentTime").toString());
                                    dataCmccMapper.insertLastRecordTime(sensorNo, dsIdDLZ, lRTime);
                                } else {
                                    String lRTime = timestampToString(fieldsZ.get(fieldsZ.size() - 1).get("currentTime").toString());
                                    dataCmccMapper.updateLastRecordTime(sensorNo, dsIdDLZ, lRTime);
                                }
                                saveData(sensorNo + "倾斜".hashCode(), measurementDLZ, fieldsZ);
                            }
                        }

                        String measurementDLLX = "tbs_liefeng_lx";
                        String dsIdDLLX = "3330_0_5700";
                        String lastRecordTimeLX = dataCmccMapper.selectLastRecordTime(sensorNo, dsIdDLLX);
                        if (lastRecordTimeLX == null) {
                            lastRecordTimeLX = influxDBConnect.selectLastRecordTime(sensorNo + "拉线".hashCode(), measurementDLLX);
                            if (lastRecordTimeLX == null) {
                                lastRecordTimeLX = "2000-01-01 00:00:00";
                            }
                        }
                        if (lastRecordTimeLX != null) {
                            List<Map<String, Object>> fieldsLX = dataCmccMapper.selectQingXieWXByTime(sensorNo, lastRecordTimeLX);
                            if (fieldsLX != null && fieldsLX.size() > 0) {
                                System.out.println("MYMAP=================================================" + fieldsLX);
                                System.out.println("传感器编号==========================" + sensorNo);
                                for (Map<String, Object> mapField : fieldsLX) {
                                    Double value = Double.valueOf(mapField.get("value").toString());

                                    WarnPlan warnPlan = new WarnPlan("lx", BigDecimal.valueOf(value), sensorNo, 0);
                                    warnPlanMapper.insertWarnPlan(warnPlan);

                                    //告警判断
                                    String currentTime = mapField.get("currentTime") + "";
                                    String time = timestampToString(currentTime);
//                                    warnPush(sensorNo + "拉线".hashCode(), "", currentTime, value);

                                    vo.put(sensorNo + "拉线".hashCode(), "time", time);
                                    vo.put(sensorNo + "拉线".hashCode(), "value", value.toString());
                                    //联合告警任务表插入数据
                                    tabUnionMapper.insert(dsIdDLX, value,sensorNo);
                                }
                                int i = dataCmccMapper.selectIsLastRecordTime(sensorNo, dsIdDLLX);
                                if (i == 0) {
                                    String lRTime = timestampToString(fieldsLX.get(fieldsLX.size() - 1).get("currentTime").toString());
                                    dataCmccMapper.insertLastRecordTime(sensorNo, dsIdDLLX, lRTime);
                                } else {
                                    String lRTime = timestampToString(fieldsLX.get(fieldsLX.size() - 1).get("currentTime").toString());
                                    dataCmccMapper.updateLastRecordTime(sensorNo, dsIdDLLX, lRTime);
                                }
                                saveData(sensorNo + "拉线".hashCode(), measurementDLLX, fieldsLX);
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    }

    @Async("taskExecutor")
    @Scheduled(initialDelay = 8000, fixedRate = 5000)
    public void deviceOnline() {
        HashOperations<String, Object, Object> vo = stringRedisTemplate.opsForHash();
        Set<String> keys = stringRedisTemplate.keys("*");
        for (String key : keys) {
            String deviceNo = tabDeviceMapper.selectDeviceNoBySensorNo(key);
            if (null != deviceNo) {
                Map<Object, Object> entries = vo.entries(key);
                String time = entries.get("time").toString();
                //离线天数
                long l = timeDifference(time);
//                if (null == map.get(deviceNo) || "0".endsWith(map.get(deviceNo))) {
                map.put(deviceNo, l + "");
//                } else {
//                    String day = map.get(deviceNo);
//                    Long aLong = Long.valueOf(day);
//                    map.put(deviceNo, (aLong > l ? l : day) + "");
//                }
            }
        }
//        vo.putAll("deviceOnline", map);
        Set<String> strings = map.keySet();
        for (String string : strings) {
            TabOnline tabOnline = new TabOnline();
            tabOnline.setDeviceNo(string);
            tabOnline.setOfflineTime(BigDecimal.valueOf((Long.valueOf(map.get(string)))));
            TabOnline tabOnlineInfo = tabOnlineMapper.selectDeviceByNo(string);
            if (tabOnlineInfo != null) {
                tabOnline.setId(tabOnlineInfo.getId());
                tabOnlineMapper.updateByPrimaryKeySelective(tabOnline);
            } else {
                tabOnlineMapper.insertSelective(tabOnline);
                int i = tabDeviceExceptionMapper.selectDevice(string);
                if (i == 0) {
                    TabDeviceException tabDeviceException = new TabDeviceException();
                    tabDeviceException.setDeviceNo(string);
                    tabDeviceException.setDealState("1");
                    tabDeviceException.setExceptionType("1");
                    tabDeviceException.setCreateTime(new Date());
                    tabDeviceExceptionMapper.insert(tabDeviceException);
                }
            }
        }
    }

    @Async("taskExecutor")
    @Scheduled(initialDelay = 10000, fixedRate = 300000)
    public void gnssTimer() {
        List<Map<String, String>> mapList = new ArrayList<>(16);
        String account = "{\"ClientType\":\"web\",\"password\":\"f934ac120abba45c1430ed23e13b3635\",\"userNameOrEmailAddress\":\"TrialUser\",\"vercode\":\"\"}";
        Map<String, Object> post = HttpClientUtil.post(tokenUrl, account, "");
        Map<String, String> result = (Map<String, String>) post.get("result");
        String accessToken = result.get("accessToken");

        String deviceUrl = "http://mon.zhdbds.com:30007/api/services/app/Project/GetDevicesByProjectID?ProjectId=49&MonType=13&getType=0&serchType=-1&timeRange=2019-05-01%2000:00:00%20-%202019-05-01%2000:10:00&tmieType=0&deviceId=0";
        Map<String, Object> deviceMap = HttpClientUtil.get(deviceUrl, "Bearer " + accessToken);
        List<Map<String, Object>> deviceList = (List<Map<String, Object>>) deviceMap.get("jsonDevices");

        Map<String, String> recordTimeMap = null;
        String newRecordTime = null;
        try {
            recordTimeMap = UpdatePropertyUtil.getValue(recordTimePath, "recordTime");
        } catch (IOException e) {
            e.printStackTrace();
        }
        String recordTime = recordTimeMap.get("recordTime");
        try {
            newRecordTime = getNewRecordTime(recordTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        for (Map<String, Object> device : deviceList) {
            String id = device.get("id").toString();
            String deviceName = device.get("device_name").toString();

            if (null != newRecordTime && isOverTime(newRecordTime)) {
                String replaceRecordTime = recordTime.replace(" ", "%20");
                String replaceNewRecordTime = newRecordTime.replace(" ", "%20");
                Map<String, Object> dataMap = HttpClientUtil.get(gnssDataUrl + id + "&timeRange=" + replaceRecordTime + "%20-%20" + replaceNewRecordTime, "Bearer " + accessToken);
                List<Map<String, Object>> contentsList = (List<Map<String, Object>>) dataMap.get("contents");
                if (contentsList.size() > 0) {
                    List<List<String>> list = (List<List<String>>) contentsList.get(0).get("toShowTable");
                    for (List<String> strings : list) {
                        Map temp = new HashMap(16);
                        for (int i = 0; i < strings.size(); i++) {
                            temp.put(getGnssKey(i), strings.get(i));
                        }
                        temp.put("sensor_no", deviceName);
                        temp.put("type", "4");
                        mapList.add(temp);
                    }
                }
            }
        }
        if (isOverTime(newRecordTime)) {
            try {
                UpdatePropertyUtil.setValue(recordTimePath, newRecordTime, "recordTime");
            } catch (IOException e) {
                e.printStackTrace();
            }
            String s = JSONUtils.obj2json(mapList);
            net.sf.json.JSONArray data = net.sf.json.JSONArray.fromObject(s);
            byte[] serialize = SerializationUtils.serialize(data);
//            String s = JSON.toJSONString(mapList);
            rabbitTemplate.convertAndSend("yunnan.done.data", serialize);
        }
    }


    public long timeDifference(String time) {

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d1 = null;
        try {
            d1 = df.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //这样得到的差值是微秒级别
        long diff = System.currentTimeMillis() - d1.getTime();
        long days = diff / (1000 * 60 * 60 * 24);
        long minute = diff / (1000 * 60 * 60);
        return minute;
    }

    public boolean timeCompare(String startTime, String endTime) {
        return true;
    }

    public String getNewRecordTime(String recordTime) throws ParseException {
        //得到当前时间
        Calendar nowTime = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //设置成这个时间
        nowTime.setTime(sdf.parse(recordTime));
        nowTime.add(Calendar.MINUTE, addTime);
        String newRecordTime = sdf.format(nowTime.getTime());
        return newRecordTime;
    }

    public boolean isOverTime(String newRecordTime) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d1 = null;
        try {
            d1 = df.parse(newRecordTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //这样得到的差值是微秒级别
        long diff = System.currentTimeMillis() - d1.getTime();
        long minute = diff / (1000 * 60);
        if (minute >= 0) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        InfluxDBConnect influxDBConnect = new InfluxDBConnect("admin", "admin", "http://127.0.0.1:8086", "my_data");
        influxDBConnect.influxDbBuild();
        String command = "select * from tbs_liefeng_lx where sensor_no='0f030000000000c1816406' order by time desc limit 1";
        QueryResult query = influxDBConnect.query(command);
        List<Map<String, Object>> mapList = influxDBConnect.queryResultToListMap(query);
        String replace = mapList.get(0).get("time").toString().replace("T", " ");
        String sTime = replace.replace("Z", "");
        System.out.println(sTime);

    }

    public static String getGnssKey(int i) {
        switch (i) {
            case 0:
                return "time";
            case 1:
                return "X";
            case 2:
                return "Y";
            case 3:
                return "H";
            case 4:
                return "ax";
            case 5:
                return "ay";
            case 6:
                return "ah";
            default:
                return "";
        }
    }

    public void saveData(String sensorNo, String measurement, List<Map<String, Object>> fields) {
        Map<String, String> tags = new HashMap<>(16);
        tags.put("sensor_no", sensorNo);
        for (Map<String, Object> field : fields) {
            influxDBConnect.insert(measurement, tags, field);
        }
    }


    public void warnPush(String sensorNo, String temp, String time, Double value) {

        HashOperations<String, Object, Object> vo = stringRedisTemplate.opsForHash();
        Map<Object, Object> entries = vo.entries(sensorNo + temp);
        if (entries.size() != 0) {
            String time1 = entries.get("time").toString();
            Double value1 = Double.valueOf(entries.get("value").toString());

            Map<String, String> map = new HashMap<>(16);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = timestampToString(time);

            System.out.println("当前时间=======" + format + "   上一次时间==========" + time1);

            map.put("sensorNo", sensorNo);
            map.put("time", format);
            Map<String, BigDecimal> alarmMap = tabWarnSettingMapper.selectAlarm(sensorNo);
            Date warnTime = null;
            try {
                warnTime = sdf.parse(format);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //查询短信发送人员列表
            List<Map<String, Object>> personsList = tabAlarmInfoMapper.getAlarmPersons();
            Map<String, Object> messageInfo = tabAlarmInfoMapper.getMessageInfo(sensorNo);
            int level = getCuAlarmLevel(alarmMap, value);
            String lvName = "";

            switch (level){
                case 1:
                    lvName = "红色";
                    break;
                case 2:
                    lvName = "橙色";
                    break;
                case 3:
                    lvName = "黄色";
                    break;
                case 4:
                    lvName = "蓝色";
                    break;
                default:
                    lvName = "";
            }
            if (level > 0) {
                int monitorId = tabMonitorMapper.selectIdBySeonsorNo(sensorNo);
                map.put("level", String.valueOf(level));
                map.put("monitorId", String.valueOf(monitorId));
                map.put("value", String.valueOf(value));
                map.put("type", "1");
                String s = JSON.toJSONString(map);

                try {
                    webSocketServer.sendMsgToAll(s, "10");
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(messageInfo != null){
                    String projectName = messageInfo.get("project_name").toString();
                    String device_no = messageInfo.get("device_no").toString();
                    String deviceName = messageInfo.get("device_name").toString();
                    BigDecimal initial_value = alarmMap.get("initial_value") == null ? BigDecimal.ZERO : alarmMap.get("initial_value");
                    String smsContent = projectName + "监测:" + deviceName + "设备,触发" + lvName + "累计告警,设备编号为:" + device_no + ",传感器编号为:" + sensorNo + ".本次监测值为:" + value + ",本次累积变化值为:"+new BigDecimal(value).subtract(initial_value)+",监测时间:" + format + ",请尽快进行核查处理";
                    try{
                        insertAlarm(sensorNo, warnTime, level, value, monitorId, 1, smsContent);
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    // 去除重复短信发送
                    Map<String, String> phoneMap = new HashMap<>();

                    for (Map<String, Object> personInfo : personsList) {
                        String phone = personInfo.get("phone").toString();
                        String name = personInfo.get("name").toString();
                        Integer personLevel = Integer.valueOf(personInfo.get("level").toString());
                        Integer type = Integer.valueOf(personInfo.get("type").toString());
                        if (type == 4 || type == 1) {
                            if (level >= personLevel) {
                                phoneMap.put(phone, name);
                            }
                        }
                    }

                    for(Map.Entry<String, String> entry : phoneMap.entrySet()){
                        String content =  entry.getValue() + ",你好。" + smsContent;
                        SudasSmsUtil.send(entry.getKey(), content);
                        TabMsgRecord tabMsgRecord = new TabMsgRecord();
                        tabMsgRecord.setSendPerson("yunnanAdmin");
                        tabMsgRecord.setPhone(entry.getKey());
                        tabMsgRecord.setSendState(1);
                        tabMsgRecord.setContent(content);
                        tabMsgRecord.setSendWay(1);
                        tabMsgRecord.setSendTime(new Date());
                        tabMsgRecordMapper.addTabMsgRecord(tabMsgRecord);
                    }
                }
            }

            int adAlarmLevel = getAdAlarmLevel(alarmMap, value, value1);
            if (adAlarmLevel > 0) {
                if (adAlarmLevel == 0) {
                    System.out.println(adAlarmLevel);
                }
                if(value < 0){
                    System.out.println("why?");
                }
                int monitorId = tabMonitorMapper.selectIdBySeonsorNo(sensorNo);
                map.put("level", String.valueOf(adAlarmLevel));
                map.put("monitorId", String.valueOf(monitorId));
                map.put("value", String.valueOf(value));
                map.put("type", "2");
                String s = JSON.toJSONString(map);
                try {
                    webSocketServer.sendMsgToAll(s, "10");


                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(messageInfo != null){
                    String projectName = messageInfo.get("project_name").toString();
                    String device_no = messageInfo.get("device_no").toString();
                    String deviceName = messageInfo.get("device_name").toString();
                    String smsContent = projectName + "监测:" + deviceName + "设备,触发" + lvName + "相邻告警,设备编号为:" + device_no + ",传感器编号为:" + sensorNo + ".本次监测值为:" + value + ",监测时间:" + format + ",请尽快进行核查处理";
                    try{
                        insertAlarm(sensorNo, warnTime, adAlarmLevel, value, monitorId, 2, smsContent);
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    // 去除重复短信发送
                    Map<String, String> phoneMap = new HashMap<>();

                    for (Map<String, Object> personInfo : personsList) {
                        String phone = personInfo.get("phone").toString();
                        String name = personInfo.get("name").toString();
                        Integer personLevel = Integer.valueOf(personInfo.get("level").toString());
                        Integer type = Integer.valueOf(personInfo.get("type").toString());
                        if (type == 4 || type == 2) {
                            if (level >= personLevel) {
                                phoneMap.put(phone, name);
                            }
                        }
                    }

                    for(Map.Entry<String, String> entry : phoneMap.entrySet()){
                        String content = entry.getValue() + ",你好。" + smsContent;
                        SudasSmsUtil.send(entry.getKey(), content);

                        TabMsgRecord tabMsgRecord = new TabMsgRecord();
                        tabMsgRecord.setSendPerson("yunnanAdmin");
                        tabMsgRecord.setPhone(entry.getKey());
                        tabMsgRecord.setSendState(1);
                        tabMsgRecord.setContent(content);
                        tabMsgRecord.setSendWay(1);
                        tabMsgRecord.setSendTime(new Date());
                        tabMsgRecordMapper.addTabMsgRecord(tabMsgRecord);
                    }

                }
            }
            Map<String, Object> spMap = getSpAlarmLevel(alarmMap, value, value1, format, time1);
            System.out.println("spMap======================================" + spMap);
            if (null != spMap) {
                if (Integer.valueOf(spMap.get("level").toString()) > 0) {
                    String deviceNo = tabSensorMapper.selectDeviceNoBySensorNo(sensorNo);
                    TabDeviceException tabDeviceException = new TabDeviceException();
                    tabDeviceException.setCreateTime(new Date());
                    tabDeviceException.setExceptionType("2");
                    tabDeviceException.setDeviceNo(deviceNo);
                    tabDeviceException.setDataException("1");
                    tabDeviceException.setDealState("1");
                    tabDeviceException.setExceptionTimeFrom(time1);
                    tabDeviceException.setExceptionTimeTo(format);
                    tabDeviceException.setExceptionDataCurrent(value.toString());
                    tabDeviceException.setExceptionDataPre(value1.toString());
                    tabDeviceException.setRateChange(spMap.get("rate").toString());
                    tabDeviceExceptionMapper.insert(tabDeviceException);
                }
            }
        }
    }

    private int getCuAlarmLevel(Map<String, BigDecimal> alarmMap, Double value) {
        Double cuAlarm1;
        Double cuAlarm2;
        Double cuAlarm3;
        Double cuAlarm4;
        try {
            cuAlarm1 = Double.valueOf(alarmMap.get("cu_alarm1").toString());
            cuAlarm2 = Double.valueOf(alarmMap.get("cu_alarm2").toString());
            cuAlarm3 = Double.valueOf(alarmMap.get("cu_alarm3").toString());
            cuAlarm4 = Double.valueOf(alarmMap.get("cu_alarm4").toString());
        } catch (Exception e) {
            return 0;
        }

        return value > cuAlarm1 ? 1 : (value > cuAlarm2 ? 2 : (value > cuAlarm3 ? 3 : (value > cuAlarm4 ? 4 : 0)));
    }

    private int getAdAlarmLevel(Map<String, BigDecimal> alarmMap, Double value, Double lastValue) {
        Double adAlarm1;
        Double adAlarm2;
        Double adAlarm3;
        Double adAlarm4;
        try {
            adAlarm1 = Double.valueOf(alarmMap.get("ad_alarm1").toString());
            adAlarm2 = Double.valueOf(alarmMap.get("ad_alarm2").toString());
            adAlarm3 = Double.valueOf(alarmMap.get("ad_alarm3").toString());
            adAlarm4 = Double.valueOf(alarmMap.get("ad_alarm4").toString());
        } catch (Exception e) {
            return 0;
        }

        value = value - lastValue;

        return value > adAlarm1 ? 1 : (value > adAlarm2 ? 2 : (value > adAlarm3 ? 3 : (value > adAlarm4 ? 4 : 0)));
    }

    private Map<String, Object> getSpAlarmLevel(Map<String, BigDecimal> alarmMap, Double value, Double lastValue, String time, String lastTime) {
        Map<String, Object> map = new HashMap<>(16);
        Double v;
        Double spAlarm1;
        Double spAlarm2;
        Double spAlarm3;
        Double spAlarm4;
        try {
            spAlarm1 = Double.valueOf(alarmMap.get("sp_alarm1").toString());
            spAlarm2 = Double.valueOf(alarmMap.get("sp_alarm2").toString());
            spAlarm3 = Double.valueOf(alarmMap.get("sp_alarm3").toString());
            spAlarm4 = Double.valueOf(alarmMap.get("sp_alarm4").toString());
        } catch (Exception e) {
            return null;
        }
        long diff = 0;
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date myTime = df.parse(time);
            Date myLastTime = df.parse(lastTime);
            diff = myTime.getTime() - myLastTime.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Double s = diff / (1000.0 * 60 * 60);
        if (s == 0) {
            return null;
        }
        v = (value - lastValue) / s;
        int i = v > spAlarm1 ? 1 : (v > spAlarm2 ? 2 : (v > spAlarm3 ? 3 : (v > spAlarm4 ? 4 : 0)));

        map.put("level", i);
        map.put("value", value);
        map.put("lastValue", lastValue);
        map.put("time", time);
        map.put("lastTime", lastTime);
        map.put("rate", v);

        return map;
    }

    private void insertAlarm(String sensorNo, Date warnTime, int level, Double value, int monitorId, int type, String smsContent) {
        TabAlarmInfo tabAlarmInfo = new TabAlarmInfo();
        tabAlarmInfo.setSensorNo(sensorNo);
        tabAlarmInfo.setMonitoringId(monitorId);
        tabAlarmInfo.setTime(warnTime);
        tabAlarmInfo.setValue(value);
        tabAlarmInfo.setLevel(level);
        tabAlarmInfo.setAlarmType(type);
        tabAlarmInfo.setStatus(1);
        tabAlarmInfo.setUploadSend(0);
        tabAlarmInfo.setSmsContent(smsContent);
        tabAlarmInfoMapper.insertSelective(tabAlarmInfo);
    }

    private static String timestampToString(String timestamp) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(new Date(Long.valueOf(timestamp) * 1000));
        return format;
    }


}
